#include "bsf.h"
#include "bsf_interface.h"
#include "bsf_debug.h"
#include "stdio.h"
#if TRANSMITTER
BSF_Payload xdata RecvPayload; //接收缓存
BSF_Payload xdata SendPayload; //发送缓存
BSF_Payload xdata IntlPayload;
BSF_Storage StorageInfo; //存储在RAM中的信息
BSF_ChannelManager ChannelManager;
BSF_Timer Timer;
BSF_BIT IsConnectLost;
BSF_BIT TimerEnable = BSF_FALSE;
unsigned char SentContinueCounter = 0; //计数器，用于计数连续发送包的个数
//unsigned char LocalBurnOut = BSF_BURNOUT_MAX;//计数器，用于计数本时的连续计数值
unsigned char ii = 0;
unsigned short int lii = 0;
void bsf_init(void)
{

    ChannelManager.index = 0;
    ChannelManager.table = channelTable;

    for (ii = 0; ii < sizeof(BSF_Payload); ii++)
    {
        ((unsigned char *)&RecvPayload)[ii] = 0;
        ((unsigned char *)&SendPayload)[ii] = 0;
        ((unsigned char *)&IntlPayload)[ii] = 0;
    }

    //重置TAG中，老化标志位
    BSF_BURNOUT_REFILL(RecvPayload);
    BSF_BURNOUT_REFILL(SendPayload);
    BSF_BURNOUT_REFILL(IntlPayload);

    //读取存在flash中的版本号，做好版本匹配
    bsf_itf_read(0, sizeof(BSF_Storage), (unsigned char *)&StorageInfo);
    if (StorageInfo.version != BSF_VERSION)
    {
        for (ii = 0; ii < sizeof(BSF_Storage); ii++)
        {
            ((unsigned char *)&StorageInfo)[ii] = 0;
        }
        BSF_SET_ID_INT(StorageInfo, 0x0000);
        StorageInfo.version = BSF_VERSION;
        StorageInfo.match = 0;
    }
    TimerEnable = BSF_TRUE;

    if (StorageInfo.match == BSF_MATCH)
    {
        bsf_itf_setSync(StorageInfo.ID);
        bsf_debug("[T] initial finished.\n");
    }
    else
    {
        bsf_itf_setChn(0);
        bsf_debug("[T] initial finished,but no device match,set to chn[0] to match.\n");
    }

    bsf_itf_setToRx();
}

/*
* 看看是不是来的包老化信息更新一些
*/
unsigned char bsf_isRecvPaloadNewer()
{
    if (BSF_BURNOUT(IntlPayload) > Timer.BurnOutTimestampSec)
    {
        return BSF_TRUE;
    }
    else
    {
        return BSF_FALSE;
    }
}

void bsf_setNextChannel()
{
    ChannelManager.index += 1;
    if (ChannelManager.index > MAX_CHANNEL_NUM)
    {
        bsf_debug("CIRCLE\n");
        ChannelManager.index = 0;
    }
    bsf_itf_setChn(ChannelManager.table[ChannelManager.index]);
}
BSF_BIT isOriginSync = BSF_TRUE;
BSF_BIT isCountDownResetEnable = BSF_FALSE;
unsigned char bsf_match()
{
    /*阶段1通道匹配*/
    /*交换ID，发射机接收机设备均会在初始化阶段固定在通道0，此时发射机持续发射ID,接收机持续回复响应,此时接收机和发射机都可以知道对方收到了自己的包,之后双方切换syncword*/
    /*具体逻辑：发射机发射一个只包含头的包，包类型为空包，ID = 0x0000 ，
    接收机收到0x0000后，回复有效的UUID,包类型为空包。
    发射机收到有效的UUID后发送包，包类型为空包。
    接收机收到有效的UUID包后，发送有UUID的空包,接收机退出匹配状态，开始使用新的syncword。
    发射机如果一直(5秒)未收到接收机的匹配完成后的空包，重新设置为syncword=0x0000
    发射机如果一只未使用新syncword完成匹配通讯，则重置syncword
    发射机到空包后，退出匹配状态，开始使用新的syncword。
    接收机在使用新的syncword后，如果发现超过5秒未收到任何数据包，则回到默认的syncword
    */
    //在未match的时候，在初始化状态时就已经初始化了默认的通讯通道值,所以不用重复设置
    if (StorageInfo.match == BSF_MATCH)
    {
        return BSF_TRUE;
    }
    else
    {
        //匹配状态默认同步包
        if (bsf_itf_isRecvArrival())
        {
            ii = bsf_itf_recv(((unsigned char *)&IntlPayload) + 1, sizeof(BSF_Payload));
            IntlPayload.len = ii;

            if (ii < 3)
            {
                bsf_debug("[T] ERROR.\n");
                //包有问题，不做判断
            }
            //本机ID为零时，接收配对，对方ID存在，，且ID不为零，处于同步状态
            else if (BSF_IS_ID_ZERO(StorageInfo) && (BSF_TYPE(IntlPayload) == BSF_TYPE_SYNC_PACK) && !BSF_IS_ID_ZERO(IntlPayload))
            {
                //阶段1，发射机收到了UUID赋值给本地的暂存器
                bsf_debug("[T] ID Got.\n");
                BSF_SET_ID_CPY(StorageInfo, IntlPayload);
                //收到ID后就开始倒计时5秒
                isCountDownResetEnable = BSF_TRUE;
                TimerEnable = BSF_FALSE;
                BSF_SET_TIMER(Timer, SyncTimestampSec, MATCH_TIMEOUT);
                TimerEnable = BSF_TRUE;
            }
            //如果ID相同，且处于同步包状态，则说明成功配对了
            else if (BSF_IS_ID_MATCH(StorageInfo, IntlPayload) && (BSF_TYPE(IntlPayload) == BSF_TYPE_SYNC_PACK))
            {
                if (isOriginSync == BSF_TRUE)
                {

                    //unsigned char buf[16];
                    //阶段2，发射机收到了UUID,判断和本地UUID一致
                    bsf_debug("[T] MACTH OK,Try New Syncword.\n");
                    //sprintf(buf, "ID=0x%x", StorageInfo.ID);
                    //bsf_debug(buf);

                    //设置新的同步字
                    isOriginSync = BSF_FALSE;
                    bsf_itf_setSync(StorageInfo.ID);
                    bsf_itf_setToRx();

                    isCountDownResetEnable = BSF_TRUE;
                    TimerEnable = BSF_FALSE;
                    BSF_SET_TIMER(Timer, SyncTimestampSec, MATCH_TIMEOUT);
                    TimerEnable = BSF_TRUE;
                }
                else
                {
                    bsf_debug("[T] Hit ! success!!!\n");
                    StorageInfo.match = BSF_MATCH;
                    bsf_itf_save(0, (unsigned char *)&StorageInfo, sizeof(BSF_Storage));
                    return BSF_TRUE; //退出匹配，匹配成功
                }
            }
            else
            {
                //unsigned char ttt[32];
                //sprintf(ttt, "ERR:ID:%x,%x,TAG:%x\n", (unsigned int)StorageInfo.ID[1], (unsigned int)StorageInfo.ID[0], (unsigned int)IntlPayload.tag);
                //bsf_debug(ttt);
            }
        }
        else
        {
        }

        //阶段3，倒计时5秒，发射机等待从机发射机的空包不成功判断
        if ((Timer.SyncTimestampSec == 0) && (isCountDownResetEnable == BSF_TRUE))
        {
            isCountDownResetEnable = BSF_FALSE;
            bsf_debug("Sync timeout!\n");
            bsf_itf_setSyncDefault();
            bsf_itf_setToRx();
            isOriginSync = BSF_TRUE;
            //StorageInfo.ID = 0x0000;
            BSF_SET_ID_INT(StorageInfo, 0x0000);
        }

        if (Timer.RecvSendTimestamp > MATCH_TIME_THRESHOLD)
        {
            //ledToggle();
            //ID 不存在时发送sync 包，ID存在时发送空包
            //IntlPayload.ID = StorageInfo.ID;

            BSF_SET_ID_CPY(IntlPayload, StorageInfo);
            IntlPayload.len = 3; //
            BSF_TYPE_SET(IntlPayload, BSF_TYPE_SYNC_PACK);
            BSF_BURNOUTSET(IntlPayload, BSF_BURNOUT_MAX);
            bsf_itf_send(((unsigned char *)&IntlPayload) + 1, IntlPayload.len);
            bsf_itf_setToRx();

            TimerEnable = BSF_FALSE;
            BSF_RESET_TIMER(Timer, RecvSendTimestamp);
            TimerEnable = BSF_TRUE;
        }

        return BSF_FALSE;
    }
}

unsigned char bsf_do(void)
{
    if (bsf_match() != BSF_TRUE)
    {
        return BSF_PAIR; //当设备未匹配时，任何其余逻辑都不将执行,bsf_do将直接返回
    }

    /*监听数据包，并根据数据包的内容进行存储，跳频老化,及跳频工作*/
    if (bsf_itf_isRecvArrival())
    {
        //每次循环首先检查BSF的接收包状态，如果有包，则处理。
        ii = bsf_itf_recv(((unsigned char *)&IntlPayload) + 1, sizeof(BSF_Payload));
        IntlPayload.len = ii;
        if (ii < 3)
        {
            bsf_debug("[T] ERROR.\n");
            //包有问题，不做判断
        }
        else if (BSF_IS_ID_MATCH(StorageInfo, IntlPayload))
        {

            //当ID成功匹配时，将重置各个计数器值
            TimerEnable = BSF_FALSE;
            BSF_RESET_TIMER(Timer, RecvSendTimestamp); //发送接收计时器因为收到了新包，这里会清零
            BSF_RESET_TIMER(Timer, LossTimestamp);     //丢失计数器因为收到了有效的包，这里会清零
            TimerEnable = BSF_TRUE;
            IsConnectLost = BSF_FALSE; //收到包意味着连接没有丢失

            switch (BSF_TYPE(IntlPayload))
            {
            case BSF_TYPE_EMPTY_PACK:
                //收到一个空包，没有必要做任何处理
                //bsf_debug("[T]GET PACK:EMPTY.\n");
                break;
            case BSF_TYPE_PAYLOAD_NORET:
            case BSF_TYPE_PAYLOAD_RET:
                bsf_debug("[T]GET PACK:PAYLOAD.\n");
                //发射机在收到payload时，不会管是否是需要返回的
                //这里将payload直接拷贝至缓存
                if (RecvPayload.len == 0)
                {
                    for (ii = 0; ii < sizeof(BSF_Payload); ii++)
                    {
                        ((unsigned char *)&RecvPayload)[ii] = ((unsigned char *)&IntlPayload)[ii];
                    }
                }
                break;
            default:
                break;
            }
        }
        else
        {
            if (bsf_isRecvPaloadNewer() == BSF_FALSE && IsConnectLost == BSF_TRUE)
            {
                bsf_debug("[T] BURNOUT.\n");
                bsf_setNextChannel();
                IntlPayload.len = 3; //一个ID 2byte,一个tag 1byte
                //IntlPayload.ID = StorageInfo.ID;
                BSF_SET_ID_CPY(IntlPayload, StorageInfo);
                BSF_TYPE_SET(IntlPayload, BSF_TYPE_EMPTY_PACK);
                BSF_BURNOUTSET(IntlPayload, BSF_BURNOUT_MAX);
                bsf_itf_send(((unsigned char *)&IntlPayload) + 1, IntlPayload.len);
                bsf_itf_setToRx();

                TimerEnable = BSF_FALSE;
                BSF_RESET_TIMER(Timer, RecvSendTimestamp); //发送接收计时器因为跳到了新频率，要先清除掉
                BSF_RESET_TIMER(Timer, LossTimestamp);     //丢失连接计数器也要重置为0
                BSF_SET_TIMER(Timer, BurnOutTimestampSec, BSF_BURNOUT_MAX);
                TimerEnable = BSF_TRUE;
            }
            else
            {
                //do nothing
            }
        }
    }

    //超时判断有俩阈值，一个是在建立连接前，阈值会很小，帮助设备快速扫频，一个是建立连接后，阈值会变大，当连接临时丢失时不至于立即频率变化
    if (IsConnectLost == BSF_FALSE)
    {
        lii = CONNECT_TIME_THRESHOLD;
    }
    else
    {
        lii = DISCONNECT_TIME_THRESHOLD;
    }

    //超时以后，进入下一个频率，并发送个空包,如果没问题，在几个扫描周期内，就应该收到回复的空包了。以前用状态机，这里不用状态机了，代码稍有冗余
    if (Timer.LossTimestamp > lii)
    {
        //ledToggle();
        IsConnectLost = BSF_TRUE;

        bsf_setNextChannel();
        IntlPayload.len = 3; //一个ID 2byte,一个tag 1byte
        //IntlPayload.ID = StorageInfo.ID;

        BSF_SET_ID_CPY(IntlPayload, StorageInfo);
        BSF_TYPE_SET(IntlPayload, BSF_TYPE_EMPTY_PACK);
        BSF_BURNOUTSET(IntlPayload, BSF_BURNOUT_MAX);
        bsf_itf_send(((unsigned char *)&IntlPayload) + 1, IntlPayload.len);
        bsf_itf_setToRx();

        TimerEnable = BSF_FALSE;
        BSF_RESET_TIMER(Timer, RecvSendTimestamp);
        BSF_RESET_TIMER(Timer, LossTimestamp);
        BSF_SET_TIMER(Timer, BurnOutTimestampSec, BSF_BURNOUT_MAX);
        TimerEnable = BSF_TRUE;

        //bsf_debug("[T] JUMP.\n");
    }

    //在超时和连接判断以后，如果连接成功，则发送正常包，不成功，则什么都不发送,心跳包只在正常连接的时候才会发送
    if (IsConnectLost == BSF_FALSE)
    {
        /*检查载荷，并发送载荷,根据载荷的类型不同，进行不同的设置*/
        if (SendPayload.len != 0)
        {
            bsf_debug("[T]SEND PAYLOAD PACK\n");
            //如果连续发送3个包，则要等待一个有效载荷
            if (SentContinueCounter >= MAX_CONTINUE_COUNTER)
            {
                SentContinueCounter = 0;
                //SendPayload.ID = StorageInfo.ID;
                BSF_SET_ID_CPY(SendPayload, StorageInfo);
                BSF_TYPE_SET(SendPayload, BSF_TYPE_PAYLOAD_RET);
                BSF_BURNOUTSET(SendPayload, Timer.BurnOutTimestampSec);
            }
            else
            {
                //SendPayload.ID = StorageInfo.ID;
                BSF_SET_ID_CPY(SendPayload, StorageInfo);
                BSF_TYPE_SET(SendPayload, BSF_TYPE_PAYLOAD_NORET);
                BSF_BURNOUTSET(SendPayload, Timer.BurnOutTimestampSec);
            }

            bsf_itf_send(((unsigned char *)&SendPayload) + 1, SendPayload.len);
            bsf_itf_setToRx();

            SentContinueCounter++;
            SendPayload.len = 0; //不安全的清理办法，为0时，不再发送

            TimerEnable = BSF_FALSE;
            BSF_RESET_TIMER(Timer, RecvSendTimestamp); //发送接收计时器要重置
            TimerEnable = BSF_TRUE;
        }
        /*发送接收计时器空闲超过指定时间，发送空闲包*/
        else if (Timer.RecvSendTimestamp > IDEL_TIME_THRESHOLD)
        {
            //bsf_debug("[T]SEND EMPTY PACK\n");
            SentContinueCounter = 0;
            IntlPayload.len = 3; //一个ID 2byte,一个tag 1byte
            //IntlPayload.ID = StorageInfo.ID;

            BSF_SET_ID_CPY(IntlPayload, StorageInfo);
            BSF_TYPE_SET(IntlPayload, BSF_TYPE_EMPTY_PACK);
            BSF_BURNOUTSET(IntlPayload, Timer.BurnOutTimestampSec);

            bsf_itf_send(((unsigned char *)&IntlPayload) + 1, IntlPayload.len);
            bsf_itf_setToRx();

            TimerEnable = BSF_FALSE;
            BSF_RESET_TIMER(Timer, RecvSendTimestamp);
            TimerEnable = BSF_TRUE;
        }
    }
    if (IsConnectLost == BSF_FALSE)
    {
        return BSF_CONNECT;
    }
    else
    {
        return BSF_DISCONNECT;
    }
}
/*设备配对指示*/
unsigned char bsf_isMatch(void)
{
    return StorageInfo.match;
}
unsigned char bsf_isSendBufFree(void)
{
    if (SendPayload.len != 0)
    {
        return BSF_FALSE;
    }
    else
    {
        return BSF_TRUE;
    }
}

unsigned char bsf_isRecvBufNE(void)
{
    if (RecvPayload.len != 0)
    {
        return BSF_TRUE;
    }
    else
    {
        return BSF_FALSE;
    }
}

unsigned char *bsf_recvBegin(unsigned char *outLen)
{
    *outLen = RecvPayload.len - 3;
    return RecvPayload.buf;
}

void bsf_recvEnd(unsigned char isRecvOk)
{
    if (isRecvOk != BSF_FALSE)
    {
        RecvPayload.len = 0;
    }
}

unsigned char *bsf_sendBegin()
{
    return SendPayload.buf;
}

void bsf_sendEnd(unsigned char len)
{
    if (len == 0)
    {
        return;
    }
    else
    {
        SendPayload.len = len + 3;
    }
}

/*定时器每ms执行的活儿*/
void bsf_timerPerMsDo()
{
    static unsigned int ms1000 = 0;
    if (TimerEnable == BSF_TRUE)
    {
        Timer.LossTimestamp++;
        Timer.RecvSendTimestamp++;
        ms1000++;
        if (ms1000 >= 1000)
        {
            ms1000 = 0;
            if (Timer.BurnOutTimestampSec != 0)
            {
                Timer.BurnOutTimestampSec--;
            }
            if (Timer.SyncTimestampSec != 0)
            {
                Timer.SyncTimestampSec--;
            }
        }
    }
}
#endif
#if RECEIVER
BSF_Payload xdata RecvPayload; //接收缓存
BSF_Payload xdata SendPayload; //发送缓存
BSF_Payload xdata IntlPayload;
BSF_Storage StorageInfo; //存储在RAM中的信息
BSF_ChannelManager ChannelManager;
BSF_Timer Timer;
BSF_BIT IsConnectLost;
BSF_BIT TimerEnable = BSF_FALSE;
BSF_BIT MatchOnBoot = BSF_FALSE;
//unsigned char LocalBurnOut = BSF_BURNOUT_MAX;//计数器，用于计数本时的连续计数值
unsigned char ii = 0;
unsigned short int lii = 0;

/*设备配对指示*/
unsigned char bsf_isMatch(void)
{
    return StorageInfo.match;
}

void bsf_init(void)
{

    ChannelManager.index = 0;
    ChannelManager.table = channelTable;

    for (ii = 0; ii < sizeof(BSF_Payload); ii++)
    {
        ((unsigned char *)&RecvPayload)[ii] = 0;
        ((unsigned char *)&SendPayload)[ii] = 0;
        ((unsigned char *)&IntlPayload)[ii] = 0;
    }

    //重置TAG中，老化标志位
    BSF_BURNOUT_REFILL(RecvPayload);
    BSF_BURNOUT_REFILL(SendPayload);
    BSF_BURNOUT_REFILL(IntlPayload);

    //读取存在flash中的版本号，做好版本匹配
    bsf_itf_read(0, sizeof(BSF_Storage), (unsigned char *)&StorageInfo);
    if (StorageInfo.version != BSF_VERSION)
    {
        for (ii = 0; ii < sizeof(BSF_Storage); ii++)
        {
            ((unsigned char *)&StorageInfo)[ii] = 0;
        }

        //StorageInfo.ID = 0xFFAA;
        BSF_SET_ID_INT(StorageInfo, 0xFFAA);
        StorageInfo.version = BSF_VERSION;
    }
    TimerEnable = BSF_TRUE;
    MatchOnBoot = BSF_TRUE;
    BSF_SET_TIMER(Timer, SyncOnBootJobSec, MATCH_BOOT_TIMEOUT);
    bsf_itf_setChn(0);
    bsf_itf_setToRx();
}

/*
* 用以判断双方ID是否相同
*/
unsigned char bsf_isIdMatch(void)
{
    //char buf[16];

    //ID不同时，以本地为主
    //if (StorageInfo.ID == IntlPayload.ID || IntlPayload.ID == 0x0000)
    if (BSF_IS_ID_MATCH(StorageInfo, IntlPayload) || BSF_IS_ID_ZERO(IntlPayload))
    {
        return BSF_TRUE;
    }
    else
    { /*
        sprintf(buf,"RID:%d\n",IntlPayload.ID);
        bsf_debug(buf);
        sprintf(buf,"LID:%d\n",StorageInfo.ID);
        bsf_debug(buf);*/
        return BSF_FALSE;
    }
}

/*
* 看看是不是来的包老化信息更新一些
*/
unsigned char bsf_isRecvPaloadNewer()
{
    if (BSF_BURNOUT(IntlPayload) > Timer.BurnOutTimestampSec)
    {
        return BSF_TRUE;
    }
    else
    {
        return BSF_FALSE;
    }
}

void bsf_setNextChannel()
{
    ChannelManager.index += 1;
    if (ChannelManager.index > MAX_CHANNEL_NUM)
    {
        ChannelManager.index = 0;
    }
    bsf_itf_setChn(ChannelManager.table[ChannelManager.index]);
}

void bsf_sendPack()
{
    if (SendPayload.len == 0)
    {
        IntlPayload.len = 3;
        //IntlPayload.ID = StorageInfo.ID;
        BSF_SET_ID_CPY(IntlPayload, StorageInfo);
        BSF_TYPE_SET(IntlPayload, BSF_TYPE_EMPTY_PACK);
        BSF_BURNOUTSET(IntlPayload, Timer.BurnOutTimestampSec);
        bsf_itf_send(((unsigned char *)&IntlPayload) + 1, IntlPayload.len);
    }
    else
    {
        //SendPayload.ID = StorageInfo.ID;
        BSF_SET_ID_CPY(SendPayload, StorageInfo);
        BSF_TYPE_SET(SendPayload, BSF_TYPE_PAYLOAD_NORET);
        BSF_BURNOUTSET(SendPayload, Timer.BurnOutTimestampSec);
        bsf_itf_send(((unsigned char *)&SendPayload) + 1, SendPayload.len);
        SendPayload.len = 0;
    }
}

BSF_BIT isOriginSync = BSF_TRUE;
BSF_BIT isCountDownResetEnable = BSF_FALSE;

/*阶段1通道匹配*/
/*交换ID，发射机接收机设备均会在初始化阶段固定在通道0，此时发射机持续发射ID,接收机持续回复响应,此时接收机和发射机都可以知道对方收到了自己的包,之后双方切换syncword*/
/*具体逻辑：发射机发射一个只包含头的包，包类型为空包，ID = 0x0000 ，
    接收机收到0x0000后，回复有效的UUID,包类型为空包。
    发射机收到有效的UUID后发送包，包类型为空包。
    接收机收到有效的UUID包后，发送有UUID的空包,接收机退出匹配状态，开始使用新的syncword。
    发射机如果一直(5秒)未收到接收机的匹配完成后的空包，重新设置为syncword=0x0000
    发射机到空包后，退出匹配状态，开始使用新的syncword。
    接收机在使用新的syncword后，如果发现超过5秒未收到任何数据包，则回到默认的syncword
    */
//在未match的时候，在初始化状态时就已经初始化了默认的通讯通道值,所以不用重复设置
unsigned char bsf_matchDo()
{
    //设置通道为0
    //匹配状态默认同步包
    if (bsf_itf_isRecvArrival())
    {
        ledToggle();
        ii = bsf_itf_recv(((unsigned char *)&IntlPayload) + 1, sizeof(BSF_Payload));
        IntlPayload.len = ii;
        if (ii < 3)
        {
            bsf_debug("[R] ERROR.\n");
            //包有问题，不做判断
        }
        //else if (IntlPayload.ID == 0x0000)
        else if (BSF_IS_ID_ZERO(IntlPayload) && BSF_TYPE(IntlPayload) == BSF_TYPE_SYNC_PACK)
        {
            //阶段1，接收机收到了请求UUID指令，回复一个UUID

            bsf_debug("[R] New Transmitter Got.\n");
            IntlPayload.len = 3;
            //IntlPayload.ID = StorageInfo.ID;
            BSF_SET_ID_CPY(IntlPayload, StorageInfo);
            BSF_TYPE_SET(IntlPayload, BSF_TYPE_SYNC_PACK);
            BSF_BURNOUTSET(IntlPayload, Timer.BurnOutTimestampSec);
            bsf_itf_send(((unsigned char *)&IntlPayload) + 1, IntlPayload.len);
            bsf_itf_setToRx();
            //收到一个ID后，就启动定时器，避免ID占据太久
            isCountDownResetEnable = BSF_TRUE;
            TimerEnable = BSF_FALSE;
            BSF_SET_TIMER(Timer, SyncTimestampSec, MATCH_TIMEOUT);
            TimerEnable = BSF_TRUE;
        }
        //else if (StorageInfo.ID == IntlPayload.ID)
        else if (BSF_IS_ID_MATCH(StorageInfo, IntlPayload) && BSF_TYPE(IntlPayload) == BSF_TYPE_SYNC_PACK)
        {
            if (isOriginSync)
            {
                isOriginSync = BSF_FALSE;
                //阶段2，接收机看到UUID一样，发送UUID后切到新同步字等待
                bsf_debug("[R] MACTH OK,jump to new sync.\n");

                //发送需要的ID号
                IntlPayload.len = 3;
                //IntlPayload.ID = StorageInfo.ID;
                BSF_SET_ID_CPY(IntlPayload, StorageInfo);
                BSF_TYPE_SET(IntlPayload, BSF_TYPE_SYNC_PACK);
                BSF_BURNOUTSET(IntlPayload, Timer.BurnOutTimestampSec);
                bsf_itf_send(((unsigned char *)&IntlPayload) + 1, IntlPayload.len);
                bsf_itf_setSync(StorageInfo.ID);
                bsf_itf_setToRx();
                //收到ID后就开始倒计时5秒
                isCountDownResetEnable = BSF_TRUE;
                TimerEnable = BSF_FALSE;
                BSF_SET_TIMER(Timer, SyncTimestampSec, MATCH_TIMEOUT);
                TimerEnable = BSF_TRUE;
            }
            else
            {
                bsf_debug("[R] hit! sync success!\n");
                StorageInfo.match = BSF_MATCH;
                bsf_itf_save(0, (unsigned char *)&StorageInfo, sizeof(BSF_Storage));

                IntlPayload.len = 3;
                //IntlPayload.ID = StorageInfo.ID;
                BSF_SET_ID_CPY(IntlPayload, StorageInfo);
                BSF_TYPE_SET(IntlPayload, BSF_TYPE_SYNC_PACK);
                BSF_BURNOUTSET(IntlPayload, Timer.BurnOutTimestampSec);
                bsf_itf_send(((unsigned char *)&IntlPayload) + 1, IntlPayload.len);
                bsf_itf_setToRx();

                return BSF_TRUE;
            }
        }
    }

    if (Timer.SyncTimestampSec == 0 && isCountDownResetEnable == BSF_TRUE)
    {
        isCountDownResetEnable = BSF_FALSE;
        bsf_debug("[R] new channel set failed!\n");
        isOriginSync = BSF_TRUE;
        bsf_itf_setSyncDefault();
        bsf_itf_setToRx();
    }

    return BSF_FALSE;
}

unsigned char bsf_match()
{

    unsigned char ret = 0;

    if (MatchOnBoot == BSF_TRUE)
    {

        ret = bsf_matchDo();

        if (ret == BSF_TRUE)
        {
            MatchOnBoot = BSF_FALSE;
            return BSF_TRUE;
        }

        //时间耗尽后，不再进入MatchOnBoot,同时，检查下是否历史上已经match了
        if (Timer.SyncOnBootJobSec == 0)
        {
            MatchOnBoot = BSF_FALSE;
            if (StorageInfo.match == BSF_MATCH)
            {
                bsf_itf_setSync(StorageInfo.ID);
                bsf_itf_setToRx();
                return BSF_TRUE;
            }
            bsf_debug("[R] On boot match no device.\n");
            return BSF_FALSE;
        }
    }

    if (StorageInfo.match == BSF_MATCH)
    {
        return BSF_TRUE;
    }
    else
    {
        return bsf_matchDo();
    }
}

unsigned char bsf_do(void)
{
    if (bsf_match() != BSF_TRUE)
    {
        return BSF_FALSE; //当设备未匹配时，任何其余逻辑都不将执行,bsf_do将直接返回
    }

    /*监听数据包，并根据数据包的内容进行存储，跳频老化,及跳频工作*/
    if (bsf_itf_isRecvArrival())
    {
        ledToggle();
        ii = bsf_itf_recv(((unsigned char *)&IntlPayload) + 1, sizeof(BSF_Payload));
        IntlPayload.len = ii;
        if (bsf_isIdMatch())
        {
            switch (BSF_TYPE(IntlPayload))
            {
            case BSF_TYPE_EMPTY_PACK:
                bsf_sendPack();
                //bsf_debug("[R] EMPTYPACK WITH RET\n");
                bsf_itf_setToRx();
                break;
            case BSF_TYPE_PAYLOAD_NORET:
                //这里将payload直接拷贝至缓存
                if (RecvPayload.len == 0)
                {
                    for (ii = 0; ii < sizeof(BSF_Payload); ii++)
                    {
                        ((unsigned char *)&RecvPayload)[ii] = ((unsigned char *)&IntlPayload)[ii];
                    }
                }
                bsf_debug("[R] PAYLOAD WITH NO RET\n");
                break;
            case BSF_TYPE_PAYLOAD_RET:
                bsf_sendPack();
                bsf_itf_setToRx();
                //发射机在收到payload时，不会管是否是需要返回的
                //这里将payload直接拷贝至缓存
                if (RecvPayload.len == 0)
                {
                    for (ii = 0; ii < sizeof(BSF_Payload); ii++)
                    {
                        ((unsigned char *)&RecvPayload)[ii] = ((unsigned char *)&IntlPayload)[ii];
                    }
                }
                bsf_debug("[R] PAYLOAD WITH RET\n");
                break;
            default:
                break;
            }

            //当ID成功匹配时，将重置各个计数器值
            TimerEnable = BSF_FALSE;
            BSF_RESET_TIMER(Timer, LossTimestamp); //丢失计数器因为收到了有效的包，这里会清零
            TimerEnable = BSF_TRUE;
            IsConnectLost = BSF_FALSE; //收到包意味着连接没有丢失
        }
        else
        {
            if (bsf_isRecvPaloadNewer() == BSF_FALSE)
            {
                TimerEnable = BSF_FALSE;
                BSF_RESET_TIMER(Timer, LossTimestamp); //丢失连接计数器也要重置为0
                BSF_SET_TIMER(Timer, BurnOutTimestampSec, BSF_BURNOUT_MAX);
                TimerEnable = BSF_TRUE;
                IsConnectLost = BSF_TRUE; //跳频必定意味着连接丢失
                bsf_setNextChannel();
                bsf_debug("[R] burnout freq jump\n");
                //bsf_itf_setToRx();
            }
            else
            {
                //do nothing
            }
        }
    }

    //超时以后，进入下一个频率
    if (Timer.LossTimestamp > CONNECT_TIME_THRESHOLD)
    {
        //bsf_debug("[R] not connect freq jump\n");
        IsConnectLost = BSF_TRUE;

        TimerEnable = BSF_FALSE;
        BSF_RESET_TIMER(Timer, LossTimestamp);
        BSF_SET_TIMER(Timer, BurnOutTimestampSec, BSF_BURNOUT_MAX);
        TimerEnable = BSF_TRUE;
        bsf_setNextChannel();
        bsf_itf_setToRx();
        ledToggle();
    }

    return BSF_TRUE;
}
unsigned char bsf_isLinkEstablished(void)
{
    return !IsConnectLost;
}
unsigned char bsf_isSendBufFree(void)
{
    if (SendPayload.len != 0)
    {
        return BSF_FALSE;
    }
    else
    {
        return BSF_TRUE;
    }
}

unsigned char bsf_isRecvBufNE(void)
{
    if (RecvPayload.len != 0)
    {
        return BSF_TRUE;
    }
    else
    {
        return BSF_FALSE;
    }
}

unsigned char *bsf_recvBegin(unsigned char *outLen)
{
    *outLen = RecvPayload.len - 3;
    return RecvPayload.buf;
}

void bsf_recvEnd(unsigned char isRecvOk)
{
    if (isRecvOk != BSF_FALSE)
    {
        RecvPayload.len = 0;
    }
}

unsigned char *bsf_sendBegin()
{
    return SendPayload.buf;
}

void bsf_sendEnd(unsigned char len)
{
    if (len == 0)
    {
        return;
    }
    else
    {
        SendPayload.len = len + 3;
    }
}

/*定时器每ms执行的活儿*/
void bsf_timerPerMsDo()
{
    static unsigned int ms1000 = 0;
    if (TimerEnable == BSF_TRUE)
    {
        Timer.LossTimestamp++;
        Timer.RecvSendTimestamp++;
        ms1000++;
        if (ms1000 >= 1000)
        {
            ms1000 = 0;
            if (Timer.BurnOutTimestampSec != 0)
            {
                Timer.BurnOutTimestampSec--;
            }
            if (Timer.SyncTimestampSec != 0)
            {
                Timer.SyncTimestampSec--;
            }
            if (Timer.SyncOnBootJobSec != 0)
            {
                Timer.SyncOnBootJobSec--;
            }
        }
    }
}
#endif
